package com.example.tangjiangxu.fragmentdemo2;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {

    private Fragment fragmentWeixin;
    private Fragment fragmentPengyouQuan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tvWexin = (TextView) findViewById(R.id.tv_weixin);
        TextView tvPengYouQuan = (TextView) findViewById(R.id.tv_pengyouquan);
        TextView tvBackStack = (TextView) findViewById(R.id.tv_back_stack);

        tvWexin.setOnClickListener(this);
        tvPengYouQuan.setOnClickListener(this);
        tvBackStack.setOnClickListener(this);

        setDefaultFragment();
    }

    /**
     * 设置默认的Fragment
     */
    private void setDefaultFragment() {
        FragmentManager fragmentManager = getFragmentManager();
        /**
         * 事务的开启，到提交，可以做多次add、replace、remove等操作，
         * 但是同一FragmentTransaction只能commit一次
         * 否则会抱：java.lang.IllegalStateException: commit already called错误
         */
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (fragmentWeixin == null) {
            fragmentWeixin = new WeiXinFragment();
        }
        fragmentTransaction.replace(R.id.fragment_content, fragmentWeixin);
        fragmentTransaction.commit();
    }

    @Override
    public void onClick(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        switch (view.getId()) {
            case R.id.tv_weixin:
                if (fragmentWeixin == null) {
                    fragmentWeixin = new WeiXinFragment();
                }
                fragmentTransaction.replace(R.id.fragment_content, fragmentWeixin);
                fragmentTransaction.commit();
                break;
            case R.id.tv_pengyouquan:
                if (fragmentPengyouQuan == null) {
                     fragmentPengyouQuan = new PengYouQuanFragment();
                }
                fragmentTransaction.replace(R.id.fragment_content, fragmentPengyouQuan);
                fragmentTransaction.commit();
                break;
            case R.id.tv_back_stack:
                Intent intent = new Intent(MainActivity.this, BackStackActivity.class);
                startActivity(intent);
                break;
        }

    }
}
